package directmemory;

import sun.misc.Unsafe;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * @author ZhengDp
 * @Date 2023/5/12 22:40
 */
public class DirectMemory_Demo3 {
    static int _1Gb = 1024*1024*1024;
    public static void main(String[] args) throws IOException {
        Unsafe unsafe = getUnsafe();
        // 分配内存的相关方法  base : 分配的内存地址
        long base = unsafe.allocateMemory(_1Gb);
        // 设置内存地址
        unsafe.setMemory(base,_1Gb,(byte)0);
        System.in.read();
        // 释放内存
        unsafe.freeMemory(base);
        System.in.read();
    }

    public static Unsafe getUnsafe(){
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            return (Unsafe) f.get(null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}

